<?php
/**
 * Created by PhpStorm.
 * User: jjj
 * Date: 2018/1/4
 * Time: 14:08
 */

namespace app\teacher\behaviour;


use app\common\model\teacher\Teacher;
use app\teacher\lib\ApiResponse;
use think\Cache;
use think\Env;
use think\Request;
use traits\controller\Jump;

class Auth
{
    use Jump;

    private static $PublicAccesses = [
        'Account' => true,
    ];

    public static function checkPublic(Request $request) {
        $ctrl = self::$PublicAccesses[$request->controller()] ?? false;
        if (is_array($ctrl)) {
            $act = $ctrl[$request->action()] ?? false;
            if ($act) return true;
        } else {
            if ($ctrl) return true;
        }

        return false;
    }

    public function run(Request $request) {

        // 检查公共接口
        if (self::checkPublic($request) == false) {
            // 检查登录
            if (self::checkPublic($request) == false) {
                $token = $request->header('token');
                $teacherId = self::checkLogin($token);
                if (empty($teacherId)) {
                    ApiResponse::error(ApiResponse::ERR_AUTH_FAILED);
                }
                $request->bind('teacherId', $teacherId);
                $request->bind('token', $token);
            }

        }

    }

    public static function saveLogin(Teacher $teacher) {
        $token = hash_hmac('sha1', 'teacher'.$teacher->id.time().mt_rand(1000,9999), $teacher->password);
        self::cache()->set($token, $teacher->id, Env::get('TokenExpired', 3600*24));
        return $token;
    }

    public static function checkLogin($token) {
        $teacherId = self::cache()->get($token);
        return $teacherId;
    }

    public static function getLogin($token) {
        $teacherId = self::cache()->get($token);
        return $teacherId;
    }

    public static function clearLogin() {
        $token = Request::instance()->token;
        self::cache()->rm($token);
    }

    private static function cache() {
        return Cache::tag('Teacher')->tag('Auth');
    }

}